package net.starwifi.duobao.web.db;

import net.starwifi.duobao.AppInitListener;
import net.starwifi.duobao.entity.*;
import net.starwifi.duobao.mvc.*;
import net.starwifi.duobao.mvc.Message;
import net.starwifi.duobao.mvc.Order;
import net.starwifi.duobao.plugin.PaymentPlugin;
import net.starwifi.duobao.service.*;
import net.starwifi.duobao.utils.IpUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;


@Controller("apiDBPayController")
@RequestMapping("/db/pay")
public class PayController extends BaseController {

    @Autowired
    DBProductService dbProductService; //夺宝产品

    @Autowired
    DBTimesService dbTimesService; //历史期

    @Autowired
    PluginService pluginService;

    @Autowired
    DBOrderService dbOrderService;

    @Autowired
    PaymentService paymentService;

    @Autowired
    MemberService memberService;

    @Autowired
    SettingService settingService;


    /**
     * 订单支付
     */
    @RequestMapping(value = "/order", method = RequestMethod.POST)
    public String db(Model model, Long productId, String timesNo, Integer num) {
        DBProduct dbProduct = dbProductService.find(productId);//夺宝产品
        Member member = memberService.getCurrent();
        if (!member.getIsEnabled()) {
            model.addAttribute("content", "账户已禁用，请联系客服");
            return "/db/error";
        }
        if (dbProduct == null) { //产品存在
            model.addAttribute("content", "该产品不存在");
            return "/db/error";
        }
        if (num == null) {
            model.addAttribute("content", "购买份数不能为空");
            return "/db/error";
        }
        if (num < 1) {
            model.addAttribute("content", "购买份数不能小于1");
            return "/db/error";
        }
        DBTimes dbTimes = dbTimesService.findByTimesNo(timesNo);
        if (dbTimes == null) { //已经结束的不能购买
            model.addAttribute("content", "该夺宝期不存在");
            return "/db/error";
        }
        if (dbTimes.getIsOver()) {
            model.addAttribute("content", "该期夺宝已经结束");
            return "/db/error";
        }
        if (num < dbTimes.getStepNum()) {
            model.addAttribute("content", "购买份数不能小于：" + dbTimes.getStepNum() + "份");
            return "/db/error";
        }
        if (num % dbTimes.getStepNum() != 0) {
            model.addAttribute("content", "必须是：" + dbTimes.getStepNum() + "的整数倍");
            return "/db/error";
        }
        if (num > dbTimes.getPurchaseQuantity()) {
            model.addAttribute("content", "超过数量限制");
            return "/db/error";
        }
        //检查库存
        if (num > (dbTimes.getQuantity() - dbTimes.getCurrentQuantity())) {
            model.addAttribute("content", "仅剩下" + (dbTimes.getQuantity() - dbTimes.getCurrentQuantity()) + "份库存");
            return "/db/error";
        }


        model.addAttribute("dbProduct", dbProduct);
        model.addAttribute("dbTimes", dbTimes);
        model.addAttribute("num", num);
        return "/db/pay-order";
    }






    /**
     * 订单确认
     */
    @ResponseBody
    @RequestMapping(value = "/create")
    public Object confirm(Long productId, String timesNo, String paymentPluginId, Integer num, HttpServletRequest request) {
        Setting sysUpdate = settingService.findByCode("sysUpdate");
        if (sysUpdate != null && sysUpdate.getConfigValue().equals("1")) {
            return Message.error("系统升级中,暂时不提供支付服务!");
        }
        DBProduct product = dbProductService.find(productId);
        if (product == null) {
            return Message.error("商品不存在");
        }
        if (num == null) {
            return Message.error("购买份数不能为空");
        }
        if (num < 1) {
            return Message.error("购买份数不能小于1");
        }
        DBTimes dbTimes = dbTimesService.findByTimesNo(timesNo);
        if (dbTimes == null) { //已经结束的不能购买
            return Message.error("该夺宝期不存在");
        }
        if (num > dbTimes.getPurchaseQuantity()) {
            return Message.error("超过数量限制");
        }
        if (dbTimes.getIsOver()) {
            return Message.error("该夺宝期已经结束,不能购买");
        }
        if (num < dbTimes.getStepNum()) {
            return Message.error("购买份数不能小于：" + dbTimes.getStepNum() + "份");
        }
        if (num % dbTimes.getStepNum() != 0) {
            return Message.error("必须是：" + dbTimes.getStepNum() + "的整数倍");
        }
        if (product.getDbTimes() == null) {
            return Message.error("该夺宝期已经下架");
        }
        if (!product.getDbTimes().getTimesNo().equals(timesNo)) {
            return Message.error("与正在进行的夺宝期号不匹配");
        }
        if (dbTimes.getCurrentQuantity() + num > dbTimes.getQuantity()) {
            return Message.error("仅剩下" + (dbTimes.getQuantity() - dbTimes.getCurrentQuantity()) + "份库存");
        }
        Member member = memberService.getCurrent();
        if (!member.getIsEnabled()) {
            return Message.error("账户已禁用，请联系客服");
        }
        if (paymentPluginId.equals("localVirtualPayPlugin")) {
            if (member.getVirtualCurrency().compareTo(dbTimes.getSingleAmount().multiply(BigDecimal.valueOf(num))) == -1) {
                return Message.createMessage(Message.error("宝币余额不足,是否立即充值?"), new HashMap<String, Object>() {{
                    put("url", "/dMember/recharge");
                }});
            }
        }
        //是否超过单用户限制
        Long sum = dbOrderService.getSum("quantity", "o.memberId=?1 and o.timesNo=?2 and o.paymentStatus=?3", new Object[]{member.getId(), dbTimes.getTimesNo(), 1});
        if (sum != null) {
            if (sum >= dbTimes.getPurchaseQuantity()) {
                return Message.error("超过该商品单用户购买限制:" + dbTimes.getPurchaseQuantity());
            }
        }
        //0元产品的单独限制
        if (dbTimes.getSingleAmount().longValue() == 0L) {
            List<net.starwifi.duobao.mvc.Order> orderBy = new ArrayList<Order>();
            orderBy.add(Order.desc("id"));
            List<DBOrder> zeroOrder = dbOrderService.getListData("o.memberId=?1 and o.timesNo=?2", new Object[]{member.getId(), dbTimes.getTimesNo()}, orderBy);
            try {
                if (zeroOrder != null) {
                    if (zeroOrder.size() > 0) {
                        DBOrder eDBOrder = zeroOrder.get(0);
                        Setting setting=settingService.findByCode("payTime");
                        int payTime=Integer.parseInt(setting.getConfigValue());
                        if (new Date().getTime() - eDBOrder.getCreateDate().getTime() < 1000 * 60 * payTime) {
                            return Message.error("0元产品订单间隔时间必须大于"+payTime+"分钟");
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                return Message.error("非法的请求");
            }
        }
        if (paymentPluginId.equals("wo3DirectPlugin")) {
            Setting BbOff = settingService.findByCode("BbOff");
            if (BbOff.getConfigValue().equals("1")) {
                return Message.error("亲爱的用户：宝币系统正在升级中，暂时无法充值，升级期间，宝币消费仍然能够继续使用！");
            }
            List<net.starwifi.duobao.mvc.Order> orderBy = new ArrayList<Order>();
            orderBy.add(Order.desc("id"));
            List<DBOrder> zeroOrder = dbOrderService.getListData("o.memberId=?1 and o.timesNo=?2", new Object[]{member.getId(), dbTimes.getTimesNo()}, orderBy);
            try {
                if (zeroOrder != null) {
                    if (zeroOrder.size() > 0) {
                        DBOrder eDBOrder = zeroOrder.get(0);
                        Setting setting=settingService.findByCode("payTime");
                        int payTime=Integer.parseInt(setting.getConfigValue());
                        if (new Date().getTime() - eDBOrder.getCreateDate().getTime() < 1000 * 60 * payTime) {
                            return Message.error("同产品订单间隔时间必须大于"+payTime+"分钟");
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                return Message.error("非法的请求");
            }

        }
        String orderSn = AppInitListener.idGenerate.getID().toString();
        String ip = IpUtils.getIpAddr(request);
        String ipAddress = IpUtils.getIpAddress(ip);
        final DBOrder order = dbOrderService.build(product, orderSn, timesNo, num, ip, ipAddress, paymentPluginId);
        return Message.createMessage(Message.success("success"), new HashMap<String, Object>() {{
            put("order", order);
        }});
    }


    /**
     * 获取支付签名信息
     */
    @RequestMapping(value = "/submit", method = RequestMethod.POST)
    @ResponseBody
    public Object submit(Long orderId, String paymentPluginId, HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        Member member = memberService.getCurrent();
        if (member == null) {
            return Message.error("用户不存在");
        }
        if (!member.getIsEnabled()) {
            return Message.error("账户已禁用，请联系客服");
        }
        PaymentPlugin paymentPlugin = pluginService.getPaymentPlugin(paymentPluginId);
        if (paymentPlugin == null || !paymentPlugin.getIsEnabled()) {
            return Message.error("支付插件错误");
        }

        DBOrder order = dbOrderService.find(orderId);
        if (order == null) {
            return Message.error("订单不存在");
        }

        if (order.getOrderStatus() == 1 || order.getOrderStatus() == 2) {
            return Message.error("订单已完成,无法再支付");
        }
        if (order.getPaymentStatus() == 1) {
            return Message.error("订单已支付,无法再继续支付");
        }
        if (!order.getMemberId().equals(member.getId())) {
            return Message.error("操作非法");
        }
        if (paymentPluginId.equals("localVirtualPayPlugin")) {

            if (member.getVirtualCurrency().compareTo(order.getAmount()) == -1) {
                return Message.createMessage(Message.error("宝币余额不足,是否立即充值?"), new HashMap<String, Object>() {{
                    put("url", "/dMember/recharge");
                }});
            }

        }

        //@TODO 应该修改为 findByOrderSnAndPaymentPluginId (同一个订单，同一种支付方法只允许有一个支付单)
        Payment payment = paymentService.findByOrderSn(order.getSn());

        if (payment == null) {
            payment = new Payment();
            payment.setSn(AppInitListener.idGenerate.getID().toString()); //支付流水号码
            payment.setType(Payment.Type.db);
            payment.setMethod(Payment.Method.online);
            payment.setStatus(Payment.Status.wait);
            payment.setPaymentMethod(order.getPaymentMethodName() + Payment.PAYMENT_METHOD_SEPARATOR + paymentPlugin.getPaymentName());
            payment.setFee(BigDecimal.ZERO);
            payment.setAmount(order.getAmount());
            payment.setPaymentPluginId(paymentPluginId);
            payment.setExpire(paymentPlugin.getTimeout() != null ? DateUtils.addMinutes(new Date(), paymentPlugin.getTimeout()) : null);
            payment.setOrderId(orderId);
            payment.setOrderSn(order.getSn());
            payment.setMemberId(member.getId());
           // payment.setFlag(order.getFlag());
            paymentService.save(payment);
        }
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("type", "success");
        result.put("requestMethod", paymentPlugin.getRequestMethod());
        result.put("requestCharset", paymentPlugin.getRequestCharset());
        String desc = order.getName() + "夺宝码";
        result.put("parameterMap", paymentPlugin.getParameterMap(payment, desc, request));
        result.put("requestUrl", paymentPlugin.getRequestUrl());
        if (StringUtils.isNotEmpty(paymentPlugin.getRequestCharset())) {
            response.setContentType("text/html; charset=" + paymentPlugin.getRequestCharset());
        }
        return result;
    }
}
